<?php

class SiteController extends Controller {

    /**
     * Declares class-based actions
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        Yii::import('project.extensions.*');
        Yii::import('project.models.*');
        $root = realpath(Yii::app()->basePath . '/../../') . DIRECTORY_SEPARATOR;
        $writable_errors = array();

        $dirs = array(
            $root,
            $root . 'avatars',
            $root . 'memes',
            $root . 'tmp',
            $root . 'uploads',
            $root . 'addon_images',
            $root . 'assets',
            $root . 'protected' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'custom.php',
        );

        foreach ($dirs as $path) {
            if (!is_writable($path)) {
                $writable_errors[] = $path . ' should be writable.';
            }
        }

        $model = new InstallForm();

        if (isset($_POST['InstallForm'])) {
            $model->attributes = $_POST['InstallForm'];
            if ($model->validate()) {
                if (file_put_contents($root . 'app_config.php', '<?php' . PHP_EOL .
                                "define('" . InstallForm::CONST_APP_NAME . "', '$model->app_name');" . PHP_EOL .
                                "define('" . InstallForm::CONST_ADMIN_EMAIL . "', '$model->admin_email');" . PHP_EOL .
                                "define('" . InstallForm::CONST_DB_HOST . "', '$model->database_host');" . PHP_EOL .
                                "define('" . InstallForm::CONST_DB_NAME . "', '$model->database_name');" . PHP_EOL .
                                "define('" . InstallForm::CONST_DB_USER . "', '$model->database_username');" . PHP_EOL .
                                "define('" . InstallForm::CONST_DB_PASSWORD . "', '$model->database_password');" . PHP_EOL
                        )) {
                    Utility::setFlash('app_config.php written!', 'success');
                }

                preg_match_all('/^(?:UPDATE|SELECT|INSERT INTO|CREATE|DROP TABLE).*;$/smU', file_get_contents($root . 'dump.sql'), $sqls);
                if (isset($sqls[0]) && is_array($sqls[0])) {
                    foreach ($sqls[0] as $sql) {
                        if (!preg_match('/INSERT\s+INTO\s+[`]?user[`]?/', $sql)) {
                            $command = Yii::app()->db->createCommand($sql);
                            $command->execute();
                        }
                    }
                    Utility::setFlash('Database updated!', 'success');

                    if ($user = User::model()->findByPk(1)) {
                        $user->username = $model->admin_username;
                        $user->password = md5($model->admin_password);
                        $user->email = $model->admin_email;
                        $user->token = md5(uniqid());
                        $user->save();
                        Utility::setFlash('Admin user updated!', 'success');
                    } else {
                        $user = new User();
                        $user->user_id = 1;
                        $user->first_name = 'Super';
                        $user->last_name = 'Admin';
                        $user->username = $model->admin_username;
                        $user->password = md5($model->admin_password);
                        $user->email = $model->admin_email;
                        $user->token = md5(uniqid());
                        $user->is_active = 1;
                        $user->is_admin = 1;
                        $user->created_at = new CDbExpression('NOW()');
                        $user->save();
                        Utility::setFlash('Admin user created!', 'success');
                    }

                    $adminUrl = rtrim(substr(Yii::app()->getBaseUrl(true), 0, -7) . '/', '/') . '/' . 'admin/default';
                    Utility::setFlash("Installation successful! Please configure facebook, google, watermark and other setting from admin: <a href=\"$adminUrl\">" . $adminUrl . '</a>', 'success');
                } else {
                    Utility::setFlash('some error occured while running dump.sql', 'error');
                }

//                $this->refresh();
            }
        }
        $this->render('index', array(
            'model' => $model,
            'writable_errors' => $writable_errors,
        ));
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $name = '=?UTF-8?B?' . base64_encode($model->name) . '?=';
                $subject = '=?UTF-8?B?' . base64_encode($model->subject) . '?=';
                $headers = "From: $name <{$model->email}>\r\n" .
                        "Reply-To: {$model->email}\r\n" .
                        "MIME-Version: 1.0\r\n" .
                        "Content-type: text/plain; charset=UTF-8";

                mail(Yii::app()->params['adminEmail'], $subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

}